package com.mm.cloth.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.mm.cloth.ClothesDetailActivity;
import com.mm.cloth.LoginActivity;
import com.mm.cloth.R;
import com.mm.cloth.adapter.ClothesAdapter;
import com.mm.cloth.model.Clothes;
import com.mm.cloth.utils.LoginCheckUtil;
import com.mm.cloth.utils.TokenManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import android.app.Activity;

public class ProfileFragment extends Fragment {
    private static final String TAG = "ProfileFragment";

    // UI组件
    private ImageView ivAvatar;
    private TextView tvUsername;
    private TextView tvEmail;
    private TextView tvClothesCount;
    private TextView tvMatchCount;
    private Button btnLogout;
    private Button btnLogin; // 新增登录按钮
    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView rvFavoriteClothes;
    private TextView tvEmptyFavorites;

    // 数据
    private ClothesAdapter clothesAdapter;
    private List<Clothes> favoriteClothes = new ArrayList<>();
    
    public ProfileFragment() {
        // 必须有一个公共的空构造函数
        Log.d(TAG, "ProfileFragment: 构造函数被调用");
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate: ProfileFragment创建");
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.d(TAG, "onCreateView: 开始创建ProfileFragment视图");
        View view = null;
        
        try {
            // 尝试加载布局
            Log.d(TAG, "onCreateView: 尝试加载fragment_profile布局");
            view = inflater.inflate(R.layout.fragment_profile, container, false);
            Log.d(TAG, "onCreateView: 成功加载布局文件");
        } catch (Exception e) {
            Log.e(TAG, "onCreateView: 加载布局文件失败", e);
            // 创建一个简单视图作为备用
            if (container != null) {
                TextView errorText = new TextView(getContext());
                errorText.setText("加载个人页面失败，请重试");
                errorText.setGravity(android.view.Gravity.CENTER);
                errorText.setPadding(20, 20, 20, 20);
                view = errorText;
            }
        }
        
        // 如果view仍然为null，创建一个空视图以防止崩溃
        if (view == null && container != null) {
            view = new View(container.getContext());
        }
        
        // 初始化视图和数据
        try {
            if (view != null) {
                initViews(view);
                setupListeners();
                loadUserInfo();
                loadFavoriteClothes();
                
                // 添加测试直接登录按钮
                addTestLoginButton(view);
            }
        } catch (Exception e) {
            Log.e(TAG, "onCreateView: 初始化视图和数据失败", e);
        }
        
        return view != null ? view : new View(getContext());
    }

    private void initViews(View view) {
        Log.d(TAG, "initViews: 初始化ProfileFragment视图组件");
        try {
            ivAvatar = view.findViewById(R.id.ivAvatar);
            tvUsername = view.findViewById(R.id.tvUsername);
            tvEmail = view.findViewById(R.id.tvEmail);
            tvClothesCount = view.findViewById(R.id.tvClothesCount);
            tvMatchCount = view.findViewById(R.id.tvMatchCount);
            btnLogout = view.findViewById(R.id.btnLogout);
            btnLogin = view.findViewById(R.id.btnLogin); // 初始化登录按钮
            swipeRefreshLayout = view.findViewById(R.id.swipeRefreshLayout);
            rvFavoriteClothes = view.findViewById(R.id.rvFavoriteClothes);
            tvEmptyFavorites = view.findViewById(R.id.tvEmptyFavorites);

            // 确保所有视图组件都已找到
            if (ivAvatar == null || tvUsername == null || tvEmail == null || tvClothesCount == null || 
                tvMatchCount == null || btnLogout == null || btnLogin == null || swipeRefreshLayout == null || 
                rvFavoriteClothes == null || tvEmptyFavorites == null) {
                Log.e(TAG, "initViews: 部分视图组件未找到");
                if (getContext() != null) {
                    Toast.makeText(getContext(), "加载个人页面组件失败", Toast.LENGTH_SHORT).show();
                }
                return;
            }

            // 设置收藏衣物的RecyclerView
            clothesAdapter = new ClothesAdapter(getContext(), favoriteClothes);
            rvFavoriteClothes.setLayoutManager(new GridLayoutManager(getContext(), 2));
            rvFavoriteClothes.setAdapter(clothesAdapter);
            Log.d(TAG, "initViews: RecyclerView设置完成");
        } catch (Exception e) {
            Log.e(TAG, "initViews: 初始化视图组件失败: " + e.getMessage(), e);
        }
    }

    private void setupListeners() {
        Log.d(TAG, "setupListeners: 设置监听器");
        try {
            // 设置下拉刷新
            if (swipeRefreshLayout != null) {
                swipeRefreshLayout.setOnRefreshListener(() -> {
                    loadUserInfo();
                    loadFavoriteClothes();
                });
            }

            // 设置退出登录按钮点击事件
            if (btnLogout != null) {
                btnLogout.setOnClickListener(v -> {
                    if (getActivity() == null) return;
                    
                    // 清除LoginCheckUtil中的登录状态
                    LoginCheckUtil.clearLoginState(getActivity());
                    
                    // 清除TokenManager中的登录状态
                    TokenManager.clearAuthInfo(getActivity());
                    
                    Log.d(TAG, "用户已退出登录，所有登录状态已清除");
                    
                    Toast.makeText(getActivity(), "已退出登录", Toast.LENGTH_SHORT).show();
                    
                    // 显示游客模式
                    displayGuestInfo();
                });
            }

            // 设置登录按钮点击事件
            if (btnLogin != null) {
                btnLogin.setOnClickListener(v -> {
                    if (getActivity() == null) return;
                    
                    // 启动登录页面
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    intent.putExtra("from_profile", true); // 标记来源
                    startActivityForResult(intent, LoginCheckUtil.LOGIN_REQUEST_CODE);
                });
            }

            // 设置收藏衣物点击事件
            if (clothesAdapter != null) {
                clothesAdapter.setOnClothesClickListener(clothes -> {
                    if (getActivity() == null) return;
                    
                    Intent intent = new Intent(getActivity(), ClothesDetailActivity.class);
                    intent.putExtra("clothes_id", clothes.getId());
                    startActivity(intent);
                });
            }
        } catch (Exception e) {
            Log.e(TAG, "setupListeners: 设置监听器失败: " + e.getMessage(), e);
        }
    }

    private void loadUserInfo() {
        Log.d(TAG, "loadUserInfo: 加载用户信息");
        if (getActivity() == null) {
            Log.e(TAG, "loadUserInfo: getActivity() 为 null，无法加载用户信息");
            return;
        }
        
        try {
            SharedPreferences sp = getActivity().getSharedPreferences("user_info", Context.MODE_PRIVATE);
            String userInfoJson = sp.getString("userInfo", null);
            
            if (userInfoJson != null) {
                try {
                    JSONObject userInfo = new JSONObject(userInfoJson);
                    
                    // 设置用户信息
                    String username = userInfo.optString("username", "用户");
                    String email = userInfo.optString("email", "未设置邮箱");
                    String avatar = userInfo.optString("avatar", "");
                    int clothesCount = userInfo.optInt("clothes_count", 0);
                    int matchCount = userInfo.optInt("match_count", 0);
                    
                    if (tvUsername != null) tvUsername.setText(username);
                    if (tvEmail != null) tvEmail.setText(email);
                    if (tvClothesCount != null) tvClothesCount.setText(String.valueOf(clothesCount));
                    if (tvMatchCount != null) tvMatchCount.setText(String.valueOf(matchCount));
                    
                    // 加载头像
                    if (ivAvatar != null && !avatar.isEmpty() && getContext() != null) {
                        Glide.with(getContext())
                                .load(avatar)
                                .apply(RequestOptions.circleCropTransform())
                                .placeholder(R.drawable.default_avatar)
                                .error(R.drawable.default_avatar)
                                .into(ivAvatar);
                    }
                    
                    // 设置按钮状态
                    if (btnLogout != null) btnLogout.setVisibility(View.VISIBLE);
                    if (btnLogin != null) btnLogin.setVisibility(View.GONE);
                    
                    Log.d(TAG, "loadUserInfo: 用户信息加载成功 - username=" + username);
                } catch (JSONException e) {
                    Log.e(TAG, "loadUserInfo: JSON解析失败", e);
                    displayGuestInfo(); // 解析失败显示游客信息
                }
            } else {
                Log.w(TAG, "loadUserInfo: 没有找到用户信息");
                displayGuestInfo(); // 无用户信息显示游客信息
            }
        } catch (Exception e) {
            Log.e(TAG, "loadUserInfo: 加载用户信息时发生异常", e);
            displayGuestInfo(); // 发生异常显示游客信息
        }
    }

    private void loadFavoriteClothes() {
        Log.d(TAG, "loadFavoriteClothes: 开始加载收藏衣物");
        if (getActivity() == null) {
            Log.e(TAG, "loadFavoriteClothes: getActivity() 为 null，无法加载收藏衣物");
            return;
        }
        
        // 显示加载中
        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setRefreshing(true);
        }
        
        // 模拟网络请求延迟
        new Thread(() -> {
            try {
                // 模拟网络延迟
                Thread.sleep(1000);
                
                // 模拟数据
                final List<Clothes> clothes = getSimulatedFavoriteClothes();
                Log.d(TAG, "loadFavoriteClothes: 模拟数据生成完成，数量：" + clothes.size());
                
                if (getActivity() != null && !getActivity().isFinishing()) {
                    getActivity().runOnUiThread(() -> {
                        try {
                            if (favoriteClothes != null) {
                                favoriteClothes.clear();
                                favoriteClothes.addAll(clothes);
                                
                                if (clothesAdapter != null) {
                                    clothesAdapter.notifyDataSetChanged();
                                    Log.d(TAG, "loadFavoriteClothes: 数据刷新完成");
                                } else {
                                    Log.e(TAG, "loadFavoriteClothes: clothesAdapter 为 null");
                                }
                            }
                            
                            // 更新UI状态
                            if (swipeRefreshLayout != null) {
                                swipeRefreshLayout.setRefreshing(false);
                            }
                            updateEmptyView();
                        } catch (Exception e) {
                            Log.e(TAG, "loadFavoriteClothes: 在UI线程更新数据时发生异常", e);
                        }
                    });
                } else {
                    Log.e(TAG, "loadFavoriteClothes: Activity已销毁或正在结束");
                }
                
            } catch (Exception e) {
                Log.e(TAG, "loadFavoriteClothes: 加载收藏衣物时发生异常", e);
                if (getActivity() != null && !getActivity().isFinishing()) {
                    getActivity().runOnUiThread(() -> {
                        if (swipeRefreshLayout != null) {
                            swipeRefreshLayout.setRefreshing(false);
                        }
                        if (getContext() != null) {
                            Toast.makeText(getContext(), "加载收藏衣物失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        }).start();
    }

    private void updateEmptyView() {
        Log.d(TAG, "updateEmptyView: 更新空视图状态");
        try {
            if (favoriteClothes == null || favoriteClothes.isEmpty()) {
                if (tvEmptyFavorites != null) tvEmptyFavorites.setVisibility(View.VISIBLE);
                if (rvFavoriteClothes != null) rvFavoriteClothes.setVisibility(View.GONE);
                Log.d(TAG, "updateEmptyView: 显示空收藏提示");
            } else {
                if (tvEmptyFavorites != null) tvEmptyFavorites.setVisibility(View.GONE);
                if (rvFavoriteClothes != null) rvFavoriteClothes.setVisibility(View.VISIBLE);
                Log.d(TAG, "updateEmptyView: 显示收藏列表");
            }
        } catch (Exception e) {
            Log.e(TAG, "updateEmptyView: 更新空视图时发生异常", e);
        }
    }

    private List<Clothes> getSimulatedFavoriteClothes() {
        Log.d(TAG, "getSimulatedFavoriteClothes: 生成模拟收藏衣物数据");
        List<Clothes> clothes = new ArrayList<>();
        
        try {
            // 模拟一些收藏的衣物数据
            clothes.add(new Clothes(1, "白色T恤", "上衣", "https://example.com/tshirt.jpg", "春夏"));
            clothes.add(new Clothes(2, "黑色牛仔裤", "裤子", "https://example.com/jeans.jpg", "四季"));
            clothes.add(new Clothes(3, "蓝色衬衫", "上衣", "https://example.com/shirt.jpg", "春秋"));
            clothes.add(new Clothes(4, "灰色卫衣", "上衣", "https://example.com/hoodie.jpg", "秋冬"));
            clothes.add(new Clothes(5, "米色风衣", "外套", "https://example.com/coat.jpg", "春秋"));
            Log.d(TAG, "getSimulatedFavoriteClothes: 成功生成" + clothes.size() + "件模拟衣物");
        } catch (Exception e) {
            Log.e(TAG, "getSimulatedFavoriteClothes: 生成模拟数据时发生异常", e);
        }
        
        return clothes;
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "onResume: ProfileFragment恢复");
        try {
            // 根据登录状态加载用户信息
            if (getActivity() != null && LoginCheckUtil.isLoggedIn(getActivity())) {
                // 用户已登录，加载用户信息
                Log.d(TAG, "onResume: 用户已登录，加载用户数据");
                loadUserInfo();
                loadFavoriteClothes();
                
                // 显示退出登录按钮，隐藏登录按钮
                if (btnLogout != null) {
                    btnLogout.setVisibility(View.VISIBLE);
                }
                if (btnLogin != null) {
                    btnLogin.setVisibility(View.GONE);
                }
            } else {
                // 用户未登录，显示默认信息
                Log.d(TAG, "onResume: 用户未登录，显示游客信息");
                displayGuestInfo();
            }
        } catch (Exception e) {
            Log.e(TAG, "onResume: 恢复时发生异常", e);
        }
    }
    
    /**
     * 显示访客信息（用户未登录时）
     */
    private void displayGuestInfo() {
        // 设置默认头像
        if (ivAvatar != null && getContext() != null) {
            Glide.with(getContext())
                    .load(R.drawable.default_avatar)
                    .apply(RequestOptions.circleCropTransform())
                    .into(ivAvatar);
        }
        
        // 设置默认文本
        if (tvUsername != null) tvUsername.setText("游客");
        if (tvEmail != null) tvEmail.setText("未登录");
        if (tvClothesCount != null) tvClothesCount.setText("0");
        if (tvMatchCount != null) tvMatchCount.setText("0");
        
        // 隐藏退出登录按钮，显示登录按钮
        if (btnLogout != null) {
            btnLogout.setVisibility(View.GONE);
        }
        if (btnLogin != null) {
            btnLogin.setVisibility(View.VISIBLE);
        }
        
        // 显示空收藏提示
        if (tvEmptyFavorites != null) {
            tvEmptyFavorites.setText("登录后可查看收藏衣物");
            tvEmptyFavorites.setVisibility(View.VISIBLE);
        }
        
        // 隐藏收藏列表
        if (rvFavoriteClothes != null) {
            rvFavoriteClothes.setVisibility(View.GONE);
        }
        
        // 清空收藏列表数据
        if (favoriteClothes != null) {
            favoriteClothes.clear();
            if (clothesAdapter != null) {
                clothesAdapter.notifyDataSetChanged();
            }
        }
    }
    
    /**
     * 添加测试直接登录按钮
     * @param view 根视图
     */
    private void addTestLoginButton(View root) {
        Button btnTestLogin = root.findViewById(R.id.btnTestLogin);
        if (btnTestLogin != null) {
            btnTestLogin.setVisibility(View.VISIBLE);
            btnTestLogin.setOnClickListener(v -> {
                try {
                    Log.d("ProfileFragment", "点击测试登录按钮，直接启动LoginActivity");
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    intent.putExtra("from_profile", true);
                    startActivityForResult(intent, LoginCheckUtil.LOGIN_REQUEST_CODE);
                } catch (Exception e) {
                    Log.e("ProfileFragment", "启动登录页面失败: " + e.getMessage(), e);
                    Toast.makeText(getActivity(), "启动登录页面失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
    
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        Log.d(TAG, "onActivityResult: requestCode=" + requestCode + ", resultCode=" + resultCode);
        
        // 处理登录请求的结果
        if (requestCode == LoginCheckUtil.LOGIN_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                // 用户成功登录，刷新用户信息
                Log.d(TAG, "用户登录成功，刷新用户信息");
                loadUserInfo();
                loadFavoriteClothes();
            } else {
                // 用户取消登录，显示游客模式
                Log.d(TAG, "用户取消登录或登录失败");
                displayGuestInfo();
            }
        }
    }
    
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.d(TAG, "onDestroyView: ProfileFragment视图销毁");
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: ProfileFragment销毁");
    }
} 